import 'dart:convert';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class Dynamics{
  int id ;
  String content ;
  String time ;
  int up ;
  int talk ;
  String username ;
  String school ;
  String nickname ;
  String icon ;
  String imgs ;

  Dynamics(this.id , this.content , this.time , this.up , this.talk , this.username , this.school , this.nickname , this.icon , this.imgs) ;

  Dynamics.fromMap(Map<String, dynamic> map) {
    id = map["id"];
    content = map["content"];
    time = map["time"];
    up = map["up"];
    talk = map["talk"];
    username = map["username"] ;
    school = map["school"] ;
    nickname = map["nickname"] ;
    icon = map["icon"] ;
    imgs = map["imgs"] ;
  }

  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      "id": id,
      "content": content,
      "time": time,
      "up": up ,
      "talk": talk ,
      "username":username ,
      "school":school ,
      "nickname":nickname ,
      "icon":icon ,
      "imgs":imgs
    };
    return map;
  }
}

class DynamicsSqlite{
  Database db;

  openSqlite() async {
    // 获取数据库文件的存储路径
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'dynamic.db');

    //根据数据库文件路径和数据库版本号创建数据库表
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute('''
          CREATE TABLE dynamics (
            id INTEGER PRIMARY KEY, 
            content TEXT, 
            time TEXT, 
            up INTEGER, 
            talk Integer ,
            nickname TEXT
            usernaem TEXT
            school TEXT
            icon TEXT
            imgs TEXT)
          ''');
        });
  }

  /**
   * 插入动态数据
   */
  insert(Dynamics dynamics) async{
    try {
      await db.insert("dynamics", dynamics.toMap()) ;
    } catch (e) {
      throw e ;
    }
  }

  Future<int> getLastId() async{
    await Sqflite.firstIntValue(await db.rawQuery("select id from dynamics order by id desc limit 1")) ;
  }

  close() async{
    await db.close() ;
  }
}